<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 200px">
          <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>

      <el-form-item label="预计验收日期" style="width: 308px">
        <el-date-picker v-model="daterangeAcceptTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>

      <el-form-item label="立项金额">
        <div style="display: flex; align-items: center;">
          <el-input v-model="queryParams.minProjectAmount" placeholder="最小金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-right: 10px;" />
          -
          <el-input v-model="queryParams.maxProjectAmount" placeholder="最大金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-left: 10px;" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" :style="{ marginTop: userStore.isMobile ? '5px' : '0' }" plain
          @click="fastAdd">快速新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
      <el-checkbox-group v-model="selectedProps">
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
          {{ col.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
    </div>
    <el-table v-loading="loading" :data="projectList" border>
      <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
        :align="'center'"
        :show-overflow-tooltip="['contractAmount', 'settlementAmount', 'housekeeperName'].includes(col.prop)"
        :width="getWidth(col.prop)">
        <!-- 特殊列的插槽处理 -->
        <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
          <span>{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 固定操作列 -->
      <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 120 : 150" align="center"
        class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" :icon="userStore.isMobile ? '' : 'View'"
            @click="handleView(scope.row)">查看</el-button>
          <el-button link type="primary" :icon="userStore.isMobile ? '' : 'Edit'"
            @click="handleUpdate(scope.row)">修改</el-button>
          <el-button link type="primary" @click="handles(scope.row)">去处理</el-button>
          <el-button link type="primary" :icon="userStore.isMobile ? '' : 'Delete'"
            @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改绩效基本信息对话框 -->
    <el-dialog :title="title" fullscreen v-model="open" width="800px" append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
          <el-form ref="projectRef" :disabled="formDisabled" :model="form" label-position="left" :rules="rules"
            :label-width="userStore.isMobile ? '100px' : '120px'" size="large">
            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="项目名称" prop="projectName">
                  <el-input v-model="form.projectName" placeholder="请输入项目名称" style="width: 100%" />
                </el-form-item>
              </el-col>

              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="归属公司" prop="companyType">
                  <el-select @change="setCompanyTypeName" v-model="form.companyType" placeholder="请选择归属公司"
                    style="width: 100%">
                    <el-option v-for="dict in company_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>

              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="项目类型" prop="projectType">
                  <el-select @change="setProjectTypeName" v-model="form.projectType" placeholder="请选择项目类型"
                    style="width: 100%">
                    <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label"
                      :value="dict.value"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 发起人相关 -->
            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="发起人" prop="createDeptName">
                  <el-input disabled v-model="form.createUserName" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="发起人所在部门" prop="createDeptName">
                  <el-input disabled v-model="form.createDeptName" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="发起时间" prop="startDate">
                  <el-date-picker disabled clearable v-model="form.createTime" type="datetime"
                    value-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发起时间" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 金额字段 -->
            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="立项金额(元)" prop="projectAmount">
                  <el-input type="number" @wheel.native.prevent v-model="form.projectAmount" placeholder="请输入立项金额"
                    style="width: 100%">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="合同金额(元)" prop="contractAmount">
                  <el-input type="number" @wheel.native.prevent v-model="form.contractAmount" placeholder="请输入合同金额"
                    style="width: 100%">
                  </el-input>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="结算金额(元)" prop="settlementAmount">
                  <el-input type="number" disabled @wheel.native.prevent v-model="form.settlementAmount"
                    placeholder="请输入结算金额" style="width: 100%">
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>

            <!-- 其他行依此类推 -->

            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="管家婆项目" prop="housekeeperProject">
                  <el-select v-model="form.housekeeperProject" clearable filterable remote reserve-keyword
                    placeholder="请输入关键字" :remote-method="selectCompany" :loading="loadingQuery" style="width: 100%"
                    @change="setHousekeeperName">
                    <el-option v-for="item in companyList" :key="item.id" :label="item.companyName" :value="item.id" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="合同签订日期" prop="planDate">
                  <el-date-picker clearable v-model="form.planDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择合同签订日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="预计验收日期" prop="acceptTime">
                  <el-date-picker clearable v-model="form.acceptTime" type="date" value-format="YYYY-MM-DD"
                    placeholder="请选择预计验收日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="立项日期" prop="approvalDate">
                  <el-date-picker clearable v-model="form.approvalDate" type="date" value-format="YYYY-MM-DD"
                    placeholder="立项日期" style="width: 100%">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="客户名称" prop="customerName">
                  <el-input v-model="form.customerName" placeholder="请输入客户名称" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="客户地址" prop="customerAddress">
                  <el-input v-model="form.customerAddress" placeholder="请输入客户地址" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row :gutter="userStore.isMobile ? 10 : 21">
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="项目配合单位" prop="projectUnit">
                  <el-input v-model="form.projectUnit" placeholder="请输入项目配合单位" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="userStore.isMobile ? 24 : 7">
                <el-form-item label="阶段确认人" prop="joinPeople">
                  <el-input v-model="form.joinPeople" :disabled="true" style="width: 100%" />
                </el-form-item>
              </el-col>



            </el-row>

            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" :rows="3" placeholder="请输入备注" style="width: 100%" />
            </el-form-item>

            <el-divider style="font-size: 16px; font-weight: bold;">环节留言</el-divider>
            <el-form-item label="留言" prop="phaseRemark">
              <el-input v-model="form.phaseRemark" type="textarea" :rows="3" placeholder="请输入留言" style="width: 100%" />
            </el-form-item>

            <amountView :projectNo="amountViewProjectNo" :key="amountViewProjectNo"></amountView>

            <el-divider style="font-size: 16px; font-weight: bold;">参与人员信息</el-divider>
            <div style="margin-bottom: 10px; text-align: left;">
              <el-button type="primary" plain :icon="Plus" @click="addPerson('add')">添加参与人员</el-button>
            </div>

            <el-table v-loading="loading" :data="personList" border style="width: 100%"
              @selection-change="handleSelectionChange">
              <el-table-column label="标签页" align="center" width="180" prop="phaseName" />
              <el-table-column label="参与人" align="center" width="200" prop="participanName" />
              <el-table-column label="岗位" align="center" prop="postName" />
              <el-table-column label="开始日期" align="center" width="120" prop="startDate" />
              <el-table-column label="结束日期" align="center" prop="endDate" />
              <el-table-column label="备注" align="center" width="120" prop="remark" />
              <el-table-column label="操作员" align="center" prop="operator" />
              <el-table-column label="操作时间" align="center" prop="startDate" width="180">
                <template #default="scope">
                  <span>{{ parseTime(scope.row.createTime, "{y}-{m}-{d} {h}:{i}:{s}") }}</span>
                </template>
              </el-table-column>
              <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 100 : 220" align="center"
                class-name="small-padding fixed-width">
                <template #default="scope">
                  <el-button link type="primary" :icon="userStore.isMobile ? '' : 'Edit'"
                    @click="handleUpdateParticipan(scope.row, scope.$index, 'edit')">修改</el-button>
                  <el-button link type="primary" :icon="userStore.isMobile ? '' : 'Delete'"
                    @click="handleDeleteParticipan(scope.row, scope.$index, 'delete')">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second" v-if="!isAdd">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third" v-if="!isAdd">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four" v-if="!isAdd">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five" v-if="!isAdd">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>
        <el-tab-pane label="配套施工清单" name="six" v-if="!isAdd">
          <matching v-if="activeName == 'six'" :datas="form"></matching>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm(1)" v-if="activeName != 'six'">保存当前内容</el-button>
          <!-- v-if 为true时显示 -->
          <el-popconfirm v-if="status == 1 && projectNo" confirm-button-text="确认" cancel-button-text="取消"
            title="确认提交到下一步?" @confirm="nextPhase">
            <template #reference>
              <el-button type="primary">下一步</el-button>
            </template>
          </el-popconfirm>
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改项目参加人员子对话框 -->
    <el-dialog :title="title" v-model="openOper" :width="userStore.isMobile ? '95%' : '800px'" append-to-body>
      <el-form ref="participanRef" :model="personForm" size="large" :rules="personRules" label-width="120px">
        <!-- <el-form-item label="关联的阶段id" prop="phaseId">
          <el-input v-model="personForm.phaseId" placeholder="请输入关联的阶段id" />
        </el-form-item> -->
        <el-form-item label="参与人" prop="participantId">
          <el-select @change="setPersonName" filterable v-model="personForm.participantId" placeholder="请选择参与人"
            clearable style="width: 200px;">
            <el-option v-for="dict in userList" clearable :key="dict.userId" :label="dict.nickName"
              :value="dict.userId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参与人岗位" prop="postId">
          <el-select @change="setPostName" filterable v-model="personForm.postId" placeholder="请选择岗位" clearable
            style="width: 200px;">
            <el-option v-for="dict in posts" clearable :key="dict.postId" :label="dict.postName"
              :value="dict.postId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="开始日期" prop="startDate">
          <el-date-picker clearable v-model="personForm.startDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endDate">
          <el-date-picker clearable v-model="personForm.endDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="personForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPersonForm">确 定</el-button>
          <el-button @click="cancelPerson">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog fullscreen v-model="openView" width="1000px" append-to-body>
      <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
          <projectView :key="form.projectNo" :datas="form" :isView="isView" :column="3" :sizes="'large'"
            :personList="personList"></projectView>
        </el-tab-pane>
        <el-tab-pane label="正式清单" name="second">
          <mainList v-if="activeName == 'second'" :datas="form"></mainList>
        </el-tab-pane>
        <el-tab-pane label="管家婆出库单" name="third">
          <saleList v-if="activeName == 'third'" :datas="form"></saleList>
        </el-tab-pane>
        <el-tab-pane label="费用汇总" name="four">
          <feeList v-if="activeName == 'four'" :datas="form"></feeList>
        </el-tab-pane>
        <el-tab-pane label="清单对比" name="five" v-if="!isAdd">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>
        <el-tab-pane label="配套施工清单" name="six" v-if="!isAdd">
          <matching v-if="activeName == 'six'" :datas="form"></matching>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  syncData,
  getCompanyList,
  getAmountInfo,
  listCompany,
  listParticipan, getParticipan, delParticipan, addParticipan, updateParticipan, getStatus,
  saveUserTableConfig, getUserTableConfig
} from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser } from "@/api/system/user";
import { getCheck, getNextPermission, listDictionary, getDictionary, delDictionary, addDictionary, updateDictionary, listAllDictionary } from "@/api/project/dictionary";
import { useRouter } from 'vue-router';
const router = useRouter();


const haveNext = ref(false)
const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { company_type } = proxy.useDict("company_type");

const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const companyList = ref([]);
const open = ref(false);
const isView = ref(false);
const openView = ref(false);
const openOper = ref(false);
const openPhase = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const projectNo = ref(null)
const phasetList = ref([]);
const formDisabled = ref(true);
const currentIndex = ref(0)
const currentType = ref('')
const status = ref("1")
const currenrPhaseId = ref()
const loadingQuery = ref(false)
let currentPhase = reactive({
  phaseCode: '',
});


import { ref } from "vue";
import { updatePhase, addPhase } from "../../../api/project/project";

function handles(row, types) {
  console.log("首页跳转", row);
  if (row.phaseId == "3") {//项目实施
    router.push({
      path: '/implement/projectImplement',
      query: {
        projectNo: row.projectNo,
      }
    });

  }
  else if (row.phaseId == "4") {//项目验收
    router.push({
      path: '/accept/projectAccept',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else if (row.phaseId == "5") {//项目核算
    router.push({
      path: '/projectAccounting/accounting',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else if (row.phaseId == "2") {//立项前期
    router.push({
      path: '/approve/projecPreMange',
      query: {
        projectNo: row.projectNo,
      }
    });
  } else if (row.phaseId == "1") {//立项前期
    handleUpdate(row)
  }
  else if (row.phaseId == "6") {
    router.push({
      path: '/warranty/projectWarranty',
      query: {
        projectNo: row.projectNo,
      }
    });
  }
  else {
    proxy.$modal.msgError("暂无待处理数据");
  }
}


const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  currentConfig: {//当前环节关联的配置表

  },
  personForm: {
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    // status:2,//写死 查询上个阶段已完成的就进入立项前期阶段 1是进行中 2是已完成 
    // 新建项目的时候会默认插入一条立项阶段到立项表 点击下一步的时候会更新阶段表把当前项目当前阶段的状态
    //改为已完成  同时往阶段表插入下一个阶段 状态是1 进行中
    // phaseId: 1,//阶段字典id   1是立项 2是立项前期 3是实施 .....现在是立项阶段 查询所有已立项的项目 完成未完成都可查
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
    // contractAmount: [{ required: true, message: "合同金额不能为空", trigger: "blur" }],

  },
  personRules: {
    postId: [{ required: true, message: "岗位不能为空", trigger: "blur" }],
    participantId: [{ required: true, message: "参与人不能为空", trigger: "blur" }],
  },

  amountInfo: {
    should: null,
    actual: null,
    remaining: null,
    gjpShould: null,
    same: null
  },

});


async function nextPhase() {
  //新版点击下一步 1.下一步按钮只开给需要审核的人 隐藏与显示 获取当前配置的环节规则 请求接口校验

  let params = {
    projectNo: projectNo.value,
    id: 1//立项阶段
  }
  //校验该环节的所有配置
  const result = await getCheck(params).then(response => {//立项阶段 id写死
    console.log("立项阶段校验信息", response);
    return response
  });
  if (result.data.permission == false) {
    proxy.$modal.msgError(result.data.message);
    return
  }
  //校验通过 更新当前阶段信息


  // if (form.value.contractAmount == null || form.value.contractAmount == '') {
  //   proxy.$modal.msgError("必须填写合同金额");
  //   return
  // }

  updateForm()

  let updateParams = {
    id: currenrPhaseId.value,
  }
  const updateResult = await updatePhase(updateParams).then((response) => {
    console.log("更新阶段", response);
    return response
  });

  if (updateResult.data.status == 2) {//如果该环节已完成 插入下一个环节
    let addParams = {
      projectNo: projectNo.value,
      phaseId: 2,//立项前期
      remark: form.value.phaseRemark//留言
    }
    addPhase(addParams).then((response) => {

    })
  }
  proxy.$modal.msgSuccess("提交成功");
  status.value = 2
  open.value = false

  let currPhase = {
    projectNo: projectNo.value,
    phaseId: 1//立项阶段 
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data?.status && response.data?.status == '2') {//如果该环节已完成 跳转到下一个环节

      router.push({
        path: '/approve/projecPreMange',
        query: { projectNo: projectNo.value }
      });

    }
    else {
      getList()
    }
  });

}


function getCurrPhase(projectNo) {
  let currPhase = {
    projectNo: projectNo,
    phaseId: 1//立项阶段 
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data == null) {//没有查询到阶段信息  可以点击下一步 插入阶段信息

    } else {
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
    }
  });
}



//添加参与人员
function addPerson(type) {
  currentType.value = type
  //重置表单
  resetPer()
  // personList.value = []
  if (currentConfig.value != null) {
    personForm.value.phaseName = currentConfig.value.phaseName
    personForm.value.phaseId = currentConfig.value.id
    openOper.value = true
    title.value = "添加参与人员信息";
  } else {//请求失败 提示
    proxy.$modal.msgError("接口请求失败");
    return
  }

}

const { queryParams, form, rules, personForm, personRules, currentConfig, amountInfo } = toRefs(data);

const setHousekeeperName = (id) => {

  if (id == undefined) {
    form.value.housekeeperName = '';
    return
  }
  const filteredObjects = companyList.value.find((obj) => obj.id === id);
  form.value.housekeeperName = '';
  console.log("filteredObjects", filteredObjects);
  form.value.housekeeperName = filteredObjects?.companyName || '';
  console.log("setHousekeeperName", id, form.value.housekeeperName);
}


function selectCompany(query) {
  console.log("queryquery", query);
  loadingQuery.value = true
  let params = {
    companyName: query
  }
  listCompany(params).then((response) => {
    companyList.value = response.data
    loadingQuery.value = false
  });
}

function tets() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位1111", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

}

const setProjectTypeName = (datas) => {
  //对应的名称
  const filteredObjects = project_type.value.filter((obj) => datas.includes(obj.value));
  form.value.projectTypeName = '';
  const labels = filteredObjects.map((obj) => obj.label);
  form.value.projectTypeName = labels.length > 1 ? labels.join(',') : labels[0] || '';

};


const setCompanyTypeName = (datas) => {
  //对应的名称
  const filteredObjects = company_type.value.filter((obj) => datas.includes(obj.value));
  form.value.companyName = '';
  const labels = filteredObjects.map((obj) => obj.label);
  form.value.companyName = labels.length > 1 ? labels.join(',') : labels[0] || '';

};



/** 查询绩效基本信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAcceptTime && "" != daterangeAcceptTime) {
    // queryParams.value.params["beginAcceptTime"] = daterangeAcceptTime.value[0];
    // queryParams.value.params["endAcceptTime"] = daterangeAcceptTime.value[1];
    queryParams.value.beginAcceptTime = daterangeAcceptTime.value[0];
    queryParams.value.endAcceptTime = daterangeAcceptTime.value[1];
  }
  listProject(queryParams.value).then((response) => {
    console.log("response", response);
    projectList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
    console.log('projectList', projectList);

  });


}

// 取消按钮
function cancel() {
  open.value = false;
  openView.value = false
  reset();
  getList()
}
// 取消按钮
function cancelPerson() {
  openOper.value = false;
  resetPer();
}


//获取用户详细信息
function getUserInfo() {
  getInfo()
    .then((res) => {
      const user = res.user;
      form.value.createUserName = user.nickName;
      form.value.createUserId = user.userId;
      form.value.createDeptName = user.dept.deptName
      form.value.createDept = user.deptId
      console.log("user", form);

    })
    .catch((error) => {
      console.log("error", error);
    });

}
// 表单重置
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null,

    companyName: null,
    companyType: null,
    companyNo: null


  };
  proxy.resetForm("projectRef");
}

// 表单重置
function resetPer() {
  personForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("participanRef");

}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 同步数据 */
function handleSync() {
  syncData().then((response) => {
    proxy.$modal.msgSuccess("同步成功");
  });
}




/** 重置按钮操作 */
function resetQuery() {
  daterangeAcceptTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.minProjectAmount = null
  queryParams.value.maxProjectAmount = null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.projectNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

function setPostName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = posts.value.filter((obj) => obj.postId === id);
  // 清空 projectTypeName 字段
  personForm.value.postName = '';
  console.log("postName", filteredObjects);
  personForm.value.postName = filteredObjects[0].postName
}

function setPersonName(id) {
  // 筛选 posts.value 中符合条件的对象
  const filteredObjects = userList.value.filter((obj) => obj.userId === id);
  // 清空 projectTypeName 字段
  personForm.value.participanName = '';
  console.log("filteredObjects[0]?.nickName", filteredObjects[0]?.nickName);

  personForm.value.participanName = filteredObjects[0]?.nickName

  console.log('6666666', personList);

}

const isAdd = ref(false)
/** 新增按钮操作 */
function handleAdd() {
  projectNo.value = null
  activeName.value = "first"
  formDisabled.value = false
  reset();
  personList.value = []
  form.value.participanList = []
  isAdd.value = true
  open.value = true;
  title.value = "添加项目基本信息";
  form.value.startDate = getCurrentDateTime()
  form.value.approvalDate = getCurrentDate()
  form.value.createTime = getCurrentDateTime()
  getUserInfo()



}

function fastAdd() {

  let addParam = {
    projectName: queryParams.value.projectName,
    projectType: queryParams.value.projectType,
    approvalDate: queryParams.value.approvalDate,
    customerName: queryParams.value.customerName
  }

  if (queryParams.value.projectName == "" || queryParams.value.projectName == null) {
    proxy.$modal.msgError("请填写项目名称");
    return
  }
  queryParams.value.approvalDate = getCurrentDate()

  if (queryParams.value.projectType == "" || queryParams.value.projectType == null) {
    proxy.$modal.msgError("请选择项目类型");
    return
  }


  addProject(addParam).then((response) => {
    proxy.$modal.msgSuccess("新增成功");
    console.log("新增", response.data.projectNo);
    queryParams.value.projectName = null
    queryParams.value.approvalDate = null
    queryParams.value.projectType = null
    queryParams.value.customerName = null
    getList()
  });



}

import amountView from "../amountView.vue";
const amountRef = ref()
const amountViewProjectNo = ref(0)
import projectView from "../projectView.vue";
/** 修改按钮操作 */
async function handleUpdate(row) {
  amountViewProjectNo.value = row.projectNo
  //项目验收之后就不能再修改了
  let currPhase = {
    projectNo: row.projectNo,
    phaseId: 4//项目验收
  }
  const acceptRes = await getStatus(currPhase).then((response) => {
    return response
  });

  //已经验收的
  if (acceptRes.data?.status == '2') {
    proxy.$modal.msgError("项目已验收,不允许修改");
    return
  }


  isAdd.value = false
  activeName.value = "first"
  console.log("sssssss", row);
  projectNo.value = row.projectNo
  formDisabled.value = false
  isView.value = false
  reset();
  const _projectNo = row.projectNo || ids.value;
  personForm.projectNo = row.projectNo
  getProject(_projectNo).then((response) => {
    form.value = response.data;
    if (form.value.housekeeperName) {
      selectCompany(form.value.housekeeperName)
    }
    open.value = true;
    title.value = "修改项目基本信息";
  });
  getListParticipan(row.projectNo)
  getNextPer(row.projectNo);
}


function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);
  let params = {
    projectNo: projectNo
  }
  listParticipan(params).then((response) => {
    console.log("参与人员信息", response);
    personList.value = response.data
  });
  getCurrPhase(projectNo)

}


function handleUpdateParticipan(row, index, type) {
  currentType.value = type
  currentIndex.value = index
  //重置表单
  console.log("rowrow", row, index);
  resetPer()
  const _projectNo = row.projectNo || ids.value;
  personForm.projectNo = row.projectNo
  console.log("修改", row);
  if (row.projectNo) {

  }

  openOper.value = true
  personForm.value = row

}


function handleDeleteParticipan(row, index, type) {
  currentType.value = type
  console.log("indexindexindex", index);
  proxy.$modal
    .confirm('是否确认删除？')
    .then(async () => {
      if (row.id) {
        await delParticipan(row.id)
        getListParticipan(form.value.projectNo)
      }
      personList.value.splice(index, 1); // 删除指定索引的元素
    })
    .catch((error) => {
      // 捕获错误并提示用户
      console.error("删除操作失败", error);
    });
}

import mainList from "../mainList.vue";
import saleList from "../saleList.vue";
import feeList from "../fee.vue"
import compareMainAndSale from "../compareMainAndSale.vue"
import matching from "../matching.vue"
const activeName = ref('first')
function handleClick(item, event) {
  // activeName
  console.log("tabs页面跳转", item.paneName, event)
  activeName.value = item.paneName
}

/** 阶段管理操作 */
async function handleView(row) {
  activeName.value = "first"
  formDisabled.value = true
  projectNo.value = row.projectNo
  reset();
  getListParticipan(projectNo.value)
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
    isView.value = true
  });

}


/** 提交按钮 */
function submitForm(type) {
  console.log("参与人员", personList);

  if (form.value.acceptTime < form.value.planDate) {
    proxy.$modal.msgError("预计验收日期不能早于预计开始日期");
    return
  }


  form.value.participanList = personList.value;
  proxy.$refs["projectRef"].validate(async (valid) => {

    if (valid) {
      if (form.value.projectNo != null) {
        updateProject(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
          getListParticipan(form.value.projectNo)
        });
      } else {
        await addProject(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          console.log("新增", response.data.projectNo);

          getProject(response.data.projectNo).then((response) => {
            form.value = response.data;
            projectNo.value = response.data.projectNo
            console.log("status.value", status.value, projectNo.value);
          });

          getCurrPhase(response.data.projectNo)
          getListParticipan(response.data.projectNo)
          // open.value = false;

          // getList();
        });
      }
    }
  });
}


function updateForm() {
  updateProject(form.value).then((response) => {
  });
}





/** 提交按钮 */
function submitPersonForm() {

  if (projectNo.value) {
    proxy.$refs["participanRef"].validate(valid => {
      if (valid) {
        personForm.value.projectNo = projectNo.value
        if (personForm.value.id != null) {
          updateParticipan(personForm.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            openOper.value = false;
            getListParticipan(projectNo.value)
          });
        } else {
          addParticipan(personForm.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            openOper.value = false;
            getListParticipan(projectNo.value)
          });
        }
      }
    });

  } else {
    proxy.$refs["participanRef"].validate((valid, errors) => {
      // 验证通过，处理数据
      try {

        if (personForm.value.id != null && personForm.value.id != undefined) {
          // 查找是否有匹配的 id
          const index = personList.value.findIndex(item => item.id === personForm.value.id);
          if (index !== -1) {
            // 如果找到匹配的 id，替换对应下标的数据
            personList.value[index] = { ...personForm.value }; // 使用扩展运算符创建新对象以避免引用问题
          } else {
            // 如果没有找到匹配的 id，直接添加到列表中
            personList.value.push({ ...personForm.value });
          }
        } else {
          // 如果 id 不存在，直接添加到列表中
          if (currentType.value == 'add') {
            console.log('新增add',);
            personList.value.push({ ...personForm.value });
          }
          if (currentType.value == 'edit') {
            console.log('编辑edit',);
            personList.value[currentIndex.value] = { ...personForm.value }
          }

        }
        // getListParticipan(projectNo.value)
        // 关闭操作窗口
        openOper.value = false;

        // 提示成功
        // proxy.$modal.msgSuccess("操作成功");
      } catch (error) {
        // 捕获错误并提示用户
        console.error("操作失败", error);
        proxy.$modal.msgError("操作失败，请稍后再试");
      }
    });
  }
}




function submitPhaseForm() {
  console.log("");

}

/** 删除按钮操作 */
function handleDelete(row) {
  const _projectNos = row.projectNo || ids.value;
  proxy.$modal
    .confirm('是否确认删除绩效基本信息编号为"' + _projectNos + '"的数据项？')
    .then(function () {
      return delProject(_projectNos);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/project/export",
    {
      ...queryParams.value,
    },
    `project_${new Date().getTime()}.xlsx`
  );
}

function getCompanys() {
  // getCompanyList(queryParams.value).then((response) => {
  //   companyList.value = response.data.map(item => ({
  //     ...item, // 保留原始属性
  //     value: item.id, // 添加 value 字段
  //     label: item.companyName, // 添加 label 字段
  //   }));

  // });
}

function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day}`;
};


// 获取当前路由对象
const route = useRoute();

// 获取查询参数
const row = route.query.row;
console.log("路由。。。", row)
if (row) {
  // handleUpdate(row)
}



function getCurrPhaseConfig() {
  getDictionary(1).then(response => {//立项阶段 id写死 
    currentConfig.value = response.data;
  });
}

function getNextPer(projectNo) {
  let params = {
    projectNo: projectNo,
    id: 1//立项阶段
  }
  getNextPermission(params).then(response => {//立项阶段 id写死
    console.log("立项阶段 下一步权限", response);
    haveNext.value = response.data.permission
  });
}

getCurrPhaseConfig()


getList();
getCompanys();
tets()


onMounted(() => {
  loadUserColumnConfig()
  nextTick(() => {
    console.log("222222222222", route.query);
    if (route.query?.projectNo) {

      getProject(route.query?.projectNo).then((response) => {
        form.value = response.data;
        handleUpdate(form.value)

        // 创建一个新的 query 对象，排除 projectNo
        const { projectNo, ...restQuery } = route.query;
        // 使用 replace 更新路由，不保留 projectNo
        router.replace({
          path: route.path,
          // query: restQuery
        });
      });
    } else if (route.query?.add == 'add') {
      handleAdd()
    }



  })

});





// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },
]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);


  // 调用保存到后端的接口
  await saveUserTableConfig({ configs: selectedProps.value, type: "projectInfo" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
    case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "projectInfo" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}


import useUserStore from '@/store/modules/user'

const userStore = useUserStore()



</script>
